#include <iostream>
#include <string>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <signal.h>
#include <unistd.h>
#include <cstdlib>
#include <cassert>
#include <cstring>
#include <cerrno>
using namespace std;

int main(int argc, char* argv[])
{
    if (argc <= 2)
    {
        cerr << "Usage: " << argv[0] << "<server> <port> <backlog>" << endl;
        return 1;
    }

    const char* ip = argv[1];
    int port = atoi(argv[2]);

    int sockfd = socket( AF_INET, SOCK_STREAM, 0);
    assert(sockfd >= 0);

    struct sockaddr_in address;
    bzero(&address, sizeof(address));
    address.sin_family = AF_INET;
    // address.sin_addr.s_addr = inet_addr(ip);
    inet_pton(AF_INET, ip, &address.sin_addr); // 新的地址转换函数 peer to network
    address.sin_port =htons(port);
    int ret = bind(sockfd, (struct sockaddr*)&address, sizeof(address));
    assert (ret != -1);

    ret = listen(sockfd, 5);
    assert(ret != -1);

    sleep(20);
    struct sockaddr_in client;
    socklen_t client_addrlength = sizeof(client);
    int connfd = accept(sockfd, (struct sockaddr*)&client, &client_addrlength);
    if(connfd < 0)
    {
      cout << "errno is: " << errno << endl;
    }
    else 
    {
      // string client_ip = inet_ntoa(client.sin_addr);
      char client_ip[INET_ADDRSTRLEN];
      inet_ntop(AF_INET, &client.sin_addr, client_ip, sizeof(client_ip)); // network to peer
      int client_port = ntohs(client.sin_port);
      cout << "connected with ip: " << client_ip << " and port: " << client_port << endl;
      close(connfd);
    }

    close (sockfd);

    return 0;
}
